package com.hyyt.shopjsp.wxmg.util;

import com.hyyt.shopjsp.util.common.EnumUtils;
import com.hyyt.shopjsp.util.common.LoggerUtils;
import com.hyyt.shopjsp.util.common.StringStaticKey;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.util.redis.util.RedisDataReadUtil;
import com.hyyt.shopjsp.util.upload.FileTypeUtil;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.*;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 上传多媒体文件工具类
 */
public class WxUploadForMidea {

	/**
	 * 上传多媒体文件
	 * @author 
	 * @param  appId,  appSecret, file：上传文件,  StrType(媒体文件类型，分别有图片（image）、语音（voice）、视频（video）和缩略图（thumb）)
	 *
	 */
	public static String postSubmit(String access_token,File file, String StrType){
		String url = WxStaticKeyUtil.WX_MEDIA_UPLOAD_URL +access_token+"&type="+StrType;
		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);
		try {
			@SuppressWarnings("deprecation") MultipartEntity multipartEntity = new MultipartEntity();
			multipartEntity.addPart("filename",new FileBody(file));
			post.setEntity(multipartEntity);
			HttpResponse res = client.execute(post);
			if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
			{
				HttpEntity entity = res.getEntity();
				String strJson = EntityUtils.toString(entity, "utf-8");
				return strJson;
			}
		} catch (Exception e) {
			LoggerUtils.error(WxUploadForMidea.class,"postSubmit():"+e);
		}
		return null;
	}
	/**
	 * 下载多媒体,返回访问路径
	 * @author 
	 * @param  appId、appSecret、mideaId、filePath:图片存放路径
	 *
	 */
	public static String getMideaByMideaId(String access_token,String mideaId){
		String url = WxStaticKeyUtil.WX_MEDIA_GET_URL +access_token+"&media_id="+mideaId;
		CloseableHttpClient client = HttpClients.createDefault();
		//client.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); 
		HttpGet get = new HttpGet(url);
		//post.addHeader("Content-Type", "text/html;charset=UTF-8");
		//post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); 
		//访问路径
		String accessPath="";
		try {
			HttpResponse res = client.execute(get);
			//LoggerUtils.info(WxUploadForMidea.class,"res 编码="+res.getParams().getParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET));
			if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
			{
				HttpEntity entity = res.getEntity();
				long contentLength = entity.getContentLength();
				String contentType = entity.getContentType().toString();
				InputStream inputStream = entity.getContent();
				if(contentLength>0){
					if(contentType.indexOf("image/jpeg")>0){
//						LoggerUtils.info(WxUploadForMidea.class,"图片格式 ");
						accessPath=inputStreamToImage(inputStream,"image");
					}else if(contentType.indexOf("audio/amr")>0){
//						LoggerUtils.info(WxUploadForMidea.class,"音频格式 ");
						accessPath=inputStreamToImage(inputStream,"voice_amr");
						/* //音频文件转换器，amr格式转换为mp3格式
						String newAccessPath=accessPath.substring(0,accessPath.lastIndexOf("."));
						WxConvertMP3.changeToMp3(accessPath, newAccessPath+".mp3");
						accessPath=newAccessPath+".mp3";*/
					}else if(contentType.indexOf("audio/mp3")>0){
//						LoggerUtils.info(WxUploadForMidea.class,"音频格式 ");
						accessPath=inputStreamToImage(inputStream,"voice_mp3");
					}else if(contentType.indexOf("video/mpeg4")>0){
//						LoggerUtils.info(WxUploadForMidea.class,"视频格式 ");
						accessPath=inputStreamToImage(inputStream,"video");
					}
				}
			}
		} catch (Exception e){
			LoggerUtils.error(WxUploadForMidea.class,"getMideaByMideaId():"+e);
		}
		if(Utils.objectIsNotEmpty(accessPath)){//截取出文件名及格式
			accessPath=accessPath.substring(accessPath.indexOf("weixin"), accessPath.length());
		}
//		LoggerUtils.info(WxUploadForMidea.class,"accessPath = "+accessPath);
		return accessPath;
	}
	/**
	 * 将二进制流转换成对应的文件
	 * @author 
	 * @param in：文件流
	 * @param fileType：
	 *      图片（image）: 1M，支持JPG格式
	 *      语音（voice）：2M，播放长度不超过60s，支持AMR\MP3格式
	 *      视频（video）：10MB，支持MP4格式
	 *      缩略图（thumb）：64KB，支持JPG格式
	 */
	public static String inputStreamToImage(InputStream in,String fileType){
        // 文件存储相对文件夹路径，例如：D:/server/b2b2c/weixin/video/20170808/
        String filePath = RedisDataReadUtil.getSysConfig(StringStaticKey.FILE_UPLOAD_ROOT) + "/" + RedisDataReadUtil.getSysConfig(StringStaticKey.FILE_SYS_WX)+ "/" + fileType + "/" + FileTypeUtil.getSerial(new Date(), RedisDataReadUtil.getSysConfig(StringStaticKey.FILE_RULE)) + "/" ;
        // 文件存储相对路径，例如：weixin/video/20170808/2017120818082564954845.amr
       String returnFilePath = RedisDataReadUtil.getSysConfig(StringStaticKey.FILE_SYS_WX)+ "/" + fileType + "/" + FileTypeUtil.getSerial(new Date(), RedisDataReadUtil.getSysConfig(StringStaticKey.FILE_RULE)) + "/" ;
        try {
		    // 创建文件夹
			File sysFolderUploadNameFile = new File(filePath);
			if(!sysFolderUploadNameFile.exists()){
				sysFolderUploadNameFile.mkdirs();
			}
			// 将字符串转换成二进制，用于显示对应的文件
			File file = null;
            // 生成随机文件名：当前年月日时分秒+五位随机数（为了在实际项目中防止文件同名而进行的处理）
            String randomCode= Utils.getRandomCode();
            //生成随机数给文件命名
			if("image".equals(fileType) || "thumb".equals(fileType)){
                returnFilePath = returnFilePath + randomCode + ".jpg";
			    file = new File(filePath + randomCode + ".jpg");//可以是任何图片格式.jpg,.png等
			}else if("voice_amr".equals(fileType)){
                returnFilePath = returnFilePath + randomCode + ".amr";
				file = new File(filePath + randomCode + ".amr");
			}else if("voice_mp3".equals(fileType)){
                returnFilePath = returnFilePath + randomCode + ".mp3";
				file = new File(filePath + randomCode + ".mp3");
			}else if("video".equals(fileType)){
                returnFilePath = returnFilePath + randomCode + ".mp4";
				file = new File(filePath + randomCode + ".mp4");
			} 
			FileOutputStream fos = new FileOutputStream(file);
			byte[] b = new byte[1024]; 
			int nRead = 0;
			while ((nRead = in.read(b)) != -1) { 
				fos.write(b, 0, nRead);
			}
			fos.flush(); 
			fos.close(); 
			in.close(); 
			return returnFilePath;
		} catch (Exception e) { 
			LoggerUtils.error(WxUploadForMidea.class,"inputStreamToImage():"+e);
			return null;
		}  
    }	
}
